import base64
import json
import os
import time
import wave

import pyaudio
import requests

# 私人信息，人各有异
data = {
    'grant_type': 'client_credentials',  # 固定值
    'client_id': 'AlCr2cOiQijfSKCkEZkhLaOi',  # API Key
    'client_secret': '6EZHjN6qnphZfOy5Ri7RFqCmigbaVDuM',  # Secret Key
}


def get_token(idata: dict) -> list:
    # get app token
    apiUrl = 'https://openapi.baidu.com/oauth/2.0/token'
    try:
        r = requests.get(apiUrl, params=idata).json()
        return r.get("access_token")
    except Exception as e:
        print(e)


def get_answer(filename: str) -> list:
    apiUrl = 'http://vop.baidu.com/server_api'
    size = os.path.getsize(filename)  # 获取本地语音文件尺寸
    file1 = open(filename, "rb").read()  # 读取本地语音文件
    text = base64.b64encode(file1).decode("utf-8")  # 对读取的文件进行base64编码
    data2 = {
        "format": filename[-3:],  # 音频格式
        "rate": 16000,  # 采样率，固定值16000
        "dev_pid": 1537,  # 普通话
        "channel": 1,  # 频道，固定值1
        "token": get_token(data),
        "cuid": "123456789python",  # 随便一个值
        "len": size,  # 语音文件的尺寸
        "speech": text,  # base64编码的语音文件
    }
    # print(data2)
    try:
        r = requests.post(apiUrl, json.dumps(data2)).json()
        # print(r)
        return r.get("result")
    except Exception as e:
        print(e)


#   用Pyaudio库录制音频
#   out_file:输出音频文件名
#   rec_time:音频录制时间(秒)
def audio_record(out_file, rec_time):
    CHUNK = 1024
    FORMAT = pyaudio.paInt16  # 16bit编码格式
    CHANNELS = 1  # 单声道
    RATE = 16000  # 16000采样频率

    p = pyaudio.PyAudio()
    # 创建音频流
    stream = p.open(format=FORMAT,  # 音频流wav格式
                    channels=CHANNELS,  # 单声道
                    rate=RATE,  # 采样率16000
                    input=True,
                    frames_per_buffer=CHUNK)

    print("Start Recording...")

    frames = []  # 录制的音频流
    # 录制音频数据
    for i in range(0, int(RATE / CHUNK * rec_time)):
        idata = stream.read(CHUNK)
        frames.append(idata)

    # 录制完成
    stream.stop_stream()
    stream.close()
    p.terminate()

    print("Recording Done...")

    # 保存音频文件
    wf = wave.open(out_file, 'wb')
    wf.setnchannels(CHANNELS)
    wf.setsampwidth(p.get_sample_size(FORMAT))
    wf.setframerate(RATE)
    wf.writeframes(b''.join(frames))
    wf.close()


if __name__ == '__main__':
    print("\n\n==================================================")
    while True:
        print("\n\n==================================================")
        print("Please tell me the command(limit within 3 seconds):")
        audio_record("1.wav", 3)  # 录制语音指令
        print("Identify On Network...")
        asr_result = get_answer("1.wav")  # 识别语音指令
        if len(asr_result) != 0:  # 语音识别结果不为空，识别结果为一个list
            print("Identify Result:", asr_result[0])
            print("Start Control...")
            print("Control End...")
            if asr_result[0].find("退出") != -1:  # 如果是"退出"指令则结束程序
                print("关闭")
            time.sleep(1)  # 延时1秒
